package cn.anecansaitin.firecrafting.common.crafting;

import cn.anecansaitin.firecrafting.ModConstant;
import cn.anecansaitin.firecrafting.api.client.crafting.IJEIRecipeRender;
import cn.anecansaitin.firecrafting.client.crafting.FireBotaniaManaRecipeRender;
import cn.anecansaitin.firecrafting.common.Config;
import cn.anecansaitin.firecrafting.common.util.Directions;
import cn.anecansaitin.firecrafting.common.util.ModJsonReader;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistryEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import vazkii.botania.api.BotaniaForgeCapabilities;
import vazkii.botania.api.internal.IManaBurst;
import vazkii.botania.api.mana.IManaReceiver;

import java.util.List;
import java.util.Objects;
import java.util.Random;

public class FireBotaniaManaRecipe extends SimpleFireRecipe{
    private final EntityType<?> mana = Objects.requireNonNull(ForgeRegistries.ENTITIES.getValue(new ResourceLocation("botania", "mana_burst")));
    private final Random random = new Random();
    private final int outputs;

    public FireBotaniaManaRecipe(ResourceLocation id, ImmutableList<Block> fireBlock, NonNullList<Ingredient> inputs, int outputs) {
        super(id, fireBlock, inputs);
        this.outputs = outputs;
    }

    @Override
    public boolean doAction(List<ItemStack> stacks, BlockPos pos, Level world) {
        if (match(stacks, pos, world)) {
            for (Direction direction : Directions.ALL_SIDE)  {
                BlockEntity entity = world.getBlockEntity(pos.relative(direction));
                if (entity != null) {
                    LazyOptional<IManaReceiver> cap = entity.getCapability(BotaniaForgeCapabilities.MANA_RECEIVER, direction.getOpposite());
                    if (cap.isPresent()) {
                        IManaReceiver manaReceiver = cap.orElseThrow(RuntimeException::new);
                        if (!manaReceiver.isFull()) {
                            manaReceiver.receiveMana(outputs);
                            return true;
                        }
                    }
                }
            }

            IManaBurst entity = Objects.requireNonNull((IManaBurst) mana.create((ServerLevel) world, null, null, null, pos, MobSpawnType.TRIGGERED, true, false));
            entity.setFake(false);
            entity.setColor(16729540);
            entity.setMana(outputs);
            entity.setGravity(0);
            entity.setManaLossPerTick(4f);
            entity.setOrbitTime(0);
            entity.setMinManaLoss(80);
            entity.setStartingMana(outputs);
            entity.setBurstSourceCoords(pos);
            entity.setCollidedAt(pos.above(20));
            ((Entity)entity).lerpMotion(random.nextDouble(-0.25, 0.25), random.nextDouble(0, 0.25), random.nextDouble(-0.25, 0.25));
            world.addFreshEntity((Entity) entity);
            return true;
        }
        return false;
    }

    @Override
    public IJEIRecipeRender getRender() {
        return FireBotaniaManaRecipeRender.INSTANCE;
    }

    public int getOutputs() {
        return outputs;
    }

    @Override
    public @NotNull RecipeSerializer<?> getSerializer() {
        return ModRecipeTypes.FIRE_BOTANIA_MANA_SERIALIZER.get();
    }

    public static class Serializer extends ForgeRegistryEntry<RecipeSerializer<?>> implements RecipeSerializer<FireBotaniaManaRecipe> {
        public static final String NAME = ModConstant.MOD_ID + ":fire_botania_mana_crafting";

        //从json读取配方
        @Override
        public @NotNull FireBotaniaManaRecipe fromJson(@NotNull ResourceLocation id, @NotNull JsonObject json) {
            //获取配方物品成分
            NonNullList<Ingredient> nonnulllist = ModJsonReader.ingredientsFromJson(GsonHelper.getAsJsonArray(json, "ingredients"));
            //判断配方成分的可用性
            if (nonnulllist.isEmpty()) {
                throw new JsonParseException("火焰燃烧(植物魔法魔力)配方内没有任何原料 No ingredients for fire botania mana recipe");
            } else if (nonnulllist.size() > Config.WORLD_MAX_COUNT.get()) {
                throw new JsonParseException("火焰燃烧(植物魔法魔力)配方内的原料超出上限" + Config.WORLD_MAX_COUNT.get() + "  Too many ingredients for fire botania mana recipe. The maximum is " + Config.WORLD_MAX_COUNT.get());
            }
            //读取魔力
            int output = json.get("output").getAsInt();
            //获取可用火焰
            ImmutableList<Block> fire = ImmutableList.copyOf(ModJsonReader.blocksFromJson(json, "fire"));
            //判断火焰可用性
            if (fire.isEmpty()) {
                throw new JsonParseException("火焰燃烧(植物魔法魔力)配方内没有指定火焰 No fire block for fire botania mana recipe");
            }
            return new FireBotaniaManaRecipe(id, fire, nonnulllist, output);
        }

        //从网络读取配方
        @Nullable
        @Override
        public FireBotaniaManaRecipe fromNetwork(@NotNull ResourceLocation id, @NotNull FriendlyByteBuf buffer) {
            //获取火焰数量
            int fireCount = buffer.readVarInt();
            //创建list构造器
            ImmutableList.Builder<Block> fireBuilder = ImmutableList.builder();
            //从buffer中读取火焰
            for (int i = 0; i < fireCount; i++) {
                fireBuilder.add(Objects.requireNonNull(ForgeRegistries.BLOCKS.getValue(buffer.readResourceLocation())));
            }
            //获取产物魔力
            int output = buffer.readVarInt();
            //从buffer中获取配方成分数量并创建集合
            NonNullList<Ingredient> input = NonNullList.withSize(buffer.readVarInt(), Ingredient.EMPTY);
            //从buffer中获取指定数量成分
            for (int i = 0; i < input.size(); i++) {
                input.set(i, Ingredient.fromNetwork(buffer));
            }
            return new FireBotaniaManaRecipe(id, fireBuilder.build(), input, output);
        }

        //将配方传入网络
        @Override
        public void toNetwork(FriendlyByteBuf buffer, FireBotaniaManaRecipe recipe) {
            //获取配方火焰
            ImmutableList<Block> fireBlock = recipe.fireBlock;
            //向buffer写入火焰数量
            buffer.writeVarInt(fireBlock.size());
            //向buffer写入火焰
            fireBlock.forEach((b) -> buffer.writeResourceLocation(Objects.requireNonNull(b.getRegistryName())));
            //获取配方产物魔力
            buffer.writeVarInt(recipe.outputs);
            //获取配方成分
            NonNullList<Ingredient> inputs = recipe.inputs;
            //向buffer写入成分数量
            buffer.writeVarInt(inputs.size());
            //向buffer写入成分
            inputs.forEach((i) -> i.toNetwork(buffer));
        }
    }
}
